import { defineStore } from "pinia";
import { reqCartList,deleteCart,updateCart,addCart,reqTotalAmount } from "@/api/shopcart";
import { ElMessage } from "element-plus";
import useUserStore from "@/stores/modules/user";

let userId = useUserStore().user._id
const useShopCartStore = defineStore("ShopCart", {
  state: () => {
    return {
      shopcartInfo: {items:[]},
      count:0,
      total:0
    };
  },
  actions: {
    // 获取购物车列表
    async getCartList(id:string){
        let result = await reqCartList(id)
        if(result.code == 200){
            this.shopcartInfo = result.data
        }else{
            ElMessage.error(result.msg)
        }
    },
    // 删除商品
    async deleteShopCart(data:any){
      let result = await deleteCart(data)
      if(result.code == 200){
        ElMessage.success(result.msg)
        this.getCartList(userId)
      }else{
        ElMessage.error(result.msg)
      }
    },

    // 删除选中商品
    async deleteCheckedCart(data:any){
      let result = await deleteCart(data)
      if(result.code == 200){
        ElMessage.success(result.msg)
        this.getCartList(userId)
      }else{
        ElMessage.error(result.msg)
      }
    },
    // 添加购物车
    async addCart(data:any){
      let result = await addCart(data)
      if(result.code == 200){
        ElMessage.success(result.msg)
      }else{
        ElMessage.error(result.msg)
      }
    },

    // 修改商品数量
    async updateCart(data:any){
      let result = await updateCart(data)
      if(result.code == 200){
        this.getCartList(userId)
      }else{
        ElMessage.error(result.msg)
      }
    },
    // 获取购物车总额
    async getTotalMoney(data:any){
      let result = await reqTotalAmount(data)
      if(result.code == 200){
        this.total = result.total
        this.count = result.count
      }else{
        ElMessage.error(result.msg)
      }
    }
  },
  getters: {},
});

export default useShopCartStore;
